import React, { useEffect, useLayoutEffect, useRef } from 'react';
import _ from 'lodash';
import scroll from 'scroll';
import { connect, history } from 'umi';
import { useAliveController } from 'react-activation';
import { Tag } from 'antd';
import { MenuOutlined } from '@ant-design/icons';
import { getOriginalPath } from '@/utils/routeFormat';
import './index.less';

export default connect(
  ({ global, menu }) => ({
    collapsed: global.collapsed,
    pathname: menu.pathname,
    tagMenuList: menu.tagMenuList,
  }),
  (dispatch) => ({
    closeTagMenu: (payload) => dispatch({ type: 'menu/closeTagMenu', payload }),
  }),
)(
  ({
    collapsed,
    isMenuRender,
    positionLeft,
    isDark,
    primaryColor,
    pathname,
    tagMenuList,
    closeTagMenu,
  }) => {
    const { dropScope } = useAliveController();
    const pathnameWithTransition = getOriginalPath(pathname);
    const tagContainerRef = useRef(null);

    // 滚动处理事件
    const scrollToCurrentTag = () => {
      const containerDom = tagContainerRef.current;
      if (containerDom) {
        try {
          const containerWidth = containerDom.clientWidth;
          const containerScrollLeft = containerDom.scrollLeft;
          const childList = _.map(containerDom?.childNodes, (item) => ({
            pathname: item.dataset.pathname,
            distance: item.offsetLeft || 0,
            tagWidth: item.offsetWidth || 0,
          }));
          const index = _.findIndex(
            childList,
            ({ pathname }) => pathname === getOriginalPath(window.location.pathname),
          );
          if (index > -1) {
            const scrollMinDistance =
              childList[index].distance - (containerWidth - childList[index].tagWidth - 8);
            const scrollMaxDistance = childList[index].distance - 8;
            if (containerScrollLeft < scrollMinDistance) {
              scroll.left(containerDom, scrollMinDistance, { duration: 300 });
            } else if (containerScrollLeft > scrollMaxDistance) {
              scroll.left(containerDom, scrollMaxDistance, { duration: 300 });
            }
          }
        } catch (e) {
          console.log('异常', e);
        }
      }
    };
    const handleScrollToCurrentTag = _.throttle(scrollToCurrentTag, 500);

    // 滚动处理触发时机
    useEffect(() => {
      handleScrollToCurrentTag();
    }, [tagMenuList, pathnameWithTransition]);
    useLayoutEffect(() => {
      setTimeout(() => {
        handleScrollToCurrentTag();
      }, 500);
    }, [isMenuRender, collapsed]);
    useEffect(() => {
      window.addEventListener('resize', handleScrollToCurrentTag);
      return () => {
        window.removeEventListener('resize', handleScrollToCurrentTag, false);
      };
    }, []);

    return (
      <div
        className="route-tag-menu"
        style={_.assign(
          { left: positionLeft },
          isDark ? { boxShadow: '8px 2px 8px 0 rgba(13,13,13,.65)' } : null,
        )}
      >
        <div className="route-tag-menu-content" ref={tagContainerRef}>
          {tagMenuList.map(({ path, label, icon }, index) => (
            <Tag
              key={path}
              closable={!!index}
              data-pathname={path}
              icon={icon}
              color={path === pathnameWithTransition ? primaryColor : null}
              onClick={() => {
                if (path !== pathnameWithTransition) {
                  history.push(path);
                }
              }}
              onClose={() => {
                dropScope(path);
                closeTagMenu(path);
              }}
            >
              {label}
            </Tag>
          ))}
        </div>
      </div>
    );
  },
);
